package action.country;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utility.Uploader;
import model.dao.CountryModel;
import model.dto.Country;
import controller.Action;
import controller.ActionForward;

public class ActionUpdateCountry implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		
		Uploader up=new Uploader(request, "upload"+File.separator+"country");
		//get parameter
				int	country_id=Integer.parseInt(up.getMutilPathRequest().getParameter("country_id"));
				String country_name=up.getMutilPathRequest().getParameter("country_name");
				String country_image=up.getMutilPathRequest().getParameter("country_image");
				int page=Integer.parseInt(request.getParameter("page"));
		//get image file 
		
		boolean hasImageFile=up.upload(""+country_id);
		//setting up dto
		Country dto=new Country();
		CountryModel dao=new CountryModel();
		dto.setId(country_id);
		dto.setName(country_name);
		if(hasImageFile){
				dto.setImage(up.getPreFix()+country_id+"."+up.getExtension());//name as sequence
		}else{
			dto.setImage(country_image);//old name
		}
		
		//processing update
		if(dao.update(dto)){
			System.out.println("Updated successfully.");
		}else{
			System.out.println("Updating fail!!!");
		}
		
		//redirect to specific page
		HttpSession session=request.getSession();
		session.setAttribute("page", page);
		
		ActionForward forward=new ActionForward();
		forward.setPath("country.sp");
		forward.setRedirect(true);
		return forward;
	}

}
